﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Collections.Generic;
using Sinacor.OMM.Util;

namespace Sinacor.OMM.Deployment.Setup
{
    public partial class Conexao
    {
        #region [ Properties ]

        PreRequisitos _preRequisitos = null;
        Instalacao _instalacao = null;

        #endregion

        #region [ Constructors ]

        public Conexao()
        {
            this.InitializeComponent();
            this.ResizeMode = ResizeMode.NoResize;
        }

        public Conexao(PreRequisitos preRequisitos)
        {
            _preRequisitos = preRequisitos;

            this.InitializeComponent();
            this.ResizeMode = ResizeMode.NoResize;
        }

        #endregion

        #region [ Methods ]


        private void LoadTNSCombo()
        {
            cbTNS.ItemsSource = GetTNSNames();
        }

        private bool CheckSinacorInstalled()
        {
            bool installed = Util.Sinacor.CheckInstalled();

            this.Dispatcher.Invoke(
                    (Action)delegate()
                    {
                        lblTestingConnection.Visibility = Visibility.Visible;
                        loader01.Visibility = Visibility.Visible;

                        LoadTNSCombo();

                        LoadRegistryValues();

                        if (installed)
                        {
                            btnTestConnection.Visibility = Visibility.Hidden;
                            lblTestingConnection.Visibility = Visibility.Hidden;
                            loader01.Visibility = Visibility.Hidden;

                            txtUser.IsEnabled = false;
                            txtPassword.IsEnabled = false;
                            cbTNS.IsEnabled = false;

                            lblConnectionOK.Visibility = Visibility.Visible;

                            LoadCompanys(txtUser.Text, txtPassword.Password, cbTNS.SelectedValue.ToString());
                        }
                        else
                        {
                            btnTestConnection.Visibility = Visibility.Visible;
                            lblTestingConnection.Visibility = Visibility.Hidden;
                            loader01.Visibility = Visibility.Hidden;

                            txtUser.IsEnabled = true;
                            txtPassword.IsEnabled = true;
                            cbTNS.IsEnabled = true;

                            lblConnectionOK.Visibility = Visibility.Hidden; 
                        }

                    });

            return installed;
        }

        private void LoadRegistryValues()
        {
            Steps.InstallWindowsRegistry objRegistry = new Steps.InstallWindowsRegistry();

            txtUser.Text = objRegistry.GetRegistryValue("User", false);
            if(!string.IsNullOrEmpty(objRegistry.GetRegistryValue("Password", false))) 
                txtPassword.Password = EncryptDecrypt.Decrypt(objRegistry.GetRegistryValue("Password", false));
            cbTNS.SelectedValue = objRegistry.GetRegistryValue("Default", true);
        }

        private List<string> GetTNSNames()
        {
            Setup.Steps.OracleConnection oracleConnection = new Sinacor.OMM.Deployment.Setup.Steps.OracleConnection();
            return oracleConnection.GetTNSNames();
        }

        private void TestConnectionAsyncCallBack(IAsyncResult ar)
        {
            Func<string, string, string, bool> testConnectionDispatcher = (Func<string, string, string, bool>)ar.AsyncState;
            bool resultConnection = testConnectionDispatcher.EndInvoke(ar);

            if (resultConnection)
            {
                this.Dispatcher.Invoke(
                    (Action)delegate()
                    {
                        ledConnectionOK.Visibility = Visibility.Visible;
                        lblConnectionOK.Visibility = Visibility.Visible;
                        ledConnectionNOK.Visibility = Visibility.Hidden;
                        lblConnectionNOK.Visibility = Visibility.Hidden;
                        LoadCompanys(txtUser.Text.Trim(), txtPassword.Password.ToUpper().Trim(), cbTNS.SelectedValue.ToString());
                    });
            }
            else
            {
                this.Dispatcher.Invoke(
                    (Action)delegate()
                    {
                        ledConnectionOK.Visibility = Visibility.Hidden;
                        lblConnectionOK.Visibility = Visibility.Hidden;
                        ledConnectionNOK.Visibility = Visibility.Visible;
                        lblConnectionNOK.Visibility = Visibility.Visible;
                        cbFirm.Items.Clear();
                        cbFirm.IsEnabled = false;
                    });
            }

            this.Dispatcher.Invoke(
                    (Action)delegate()
                    {
                        lblTestingConnection.Visibility = Visibility.Hidden;
                        loader01.Visibility = Visibility.Hidden;
                        btnTestConnection.Visibility = Visibility.Visible;
                    });
        }

        private bool TestConnection(string user, string password, string tns)
        {
            Steps.OracleConnection oracleConn = new Steps.OracleConnection();
            return oracleConn.TestConnection(user, password, tns);
        }

        private List<Parameter.Entitys.Company> GetCompanys(string user, string password, string tns)
        {
            return new Steps.OracleConnection().GetCompanys(user, password, tns);
        }

        private void LoadCompanys(string user, string password, string tns)
        {
            cbFirm.Items.Clear();

            List<Parameter.Entitys.Company> itemsSource = GetCompanys(user, password, tns);
            itemsSource.Insert(0, new Parameter.Entitys.Company());

            cbFirm.DisplayMemberPath = "NomeEmpresa";
            cbFirm.SelectedValuePath = "CodigoEmpresa";
            cbFirm.ItemsSource = itemsSource;

            cbFirm.SelectedIndex = 0;

            cbFirm.IsEnabled = true;
        }

        private void UpdateConfigs()
        {
            Steps.UpdateConfig.UpdateConfigs(cbFirm.SelectedValue.ToString());
        }

        private void OpenNextStep()
        {
            if (_instalacao == null)
                _instalacao = new Instalacao(this);
            _instalacao.Show();
        }

        private void CreateRegistry()
        {
            Steps.InstallWindowsRegistry installRegistry = new Steps.InstallWindowsRegistry();
            installRegistry.CreateSinacorRegistry(txtUser.Text, EncryptDecrypt.Encrypt(txtPassword.Password), cbTNS.SelectedValue.ToString());
        }

        private void LoadAsyncCallBack(IAsyncResult ar)
        {
            Func<bool> loadDispatcher = (Func<bool>)ar.AsyncState;
            bool resultLoad = loadDispatcher.EndInvoke(ar);

            //if (resultLoad)
            //{
            //    this.Dispatcher.Invoke(
            //        (Action)delegate()
            //        {
            //            GridPrincipal.IsEnabled = true;
            //        });
            //}
            //else
            //{ }
        }

        #endregion

        #region [ Events ]

        private void btnBack_Click(object sender, RoutedEventArgs e)
        {
            _preRequisitos.Show();
            this.Hide();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (SetupBase.ShowExitConfirm())
                SetupBase.CloseMainWindow();
            else
                e.Cancel = true;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Func<bool> loadDispatcher = new Func<bool>(CheckSinacorInstalled);
            loadDispatcher.BeginInvoke(LoadAsyncCallBack, loadDispatcher);
        }

        private void btnTestConnection_Click(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(txtUser.Text))
            {
                MessageBox.Show("Digite o usuário para realizar o teste de conexão!", "Atenção", MessageBoxButton.OK);
                txtUser.Focus();
                return;
            }

            if (String.IsNullOrEmpty(txtPassword.Password))
            {
                MessageBox.Show("Digite a senha para realizar o teste de conexão!", "Atenção", MessageBoxButton.OK);
                txtPassword.Focus();
                return;
            }

            if (String.IsNullOrEmpty(cbTNS.SelectedValue.ToString()))
            {
                MessageBox.Show("Selecione o TNS para realizar o teste de conexão!", "Atenção", MessageBoxButton.OK);
                cbTNS.Focus();
                return;
            }

            btnNext.Visibility = Visibility.Hidden;
            cbFirm.ItemsSource = null;
            cbFirm.IsEnabled = false;
            btnTestConnection.Visibility = Visibility.Hidden;
            lblTestingConnection.Visibility = Visibility.Visible;
            loader01.Visibility = Visibility.Visible;
            ledConnectionOK.Visibility = Visibility.Hidden;
            lblConnectionOK.Visibility = Visibility.Hidden;
            ledConnectionNOK.Visibility = Visibility.Hidden;
            lblConnectionNOK.Visibility = Visibility.Hidden;

            Func<string, string, string, bool> testConnectionDispatcher = new Func<string, string, string, bool>(TestConnection);
            testConnectionDispatcher.BeginInvoke(txtUser.Text.Trim(), txtPassword.Password.ToUpper().Trim(), cbTNS.SelectedValue.ToString(), TestConnectionAsyncCallBack, testConnectionDispatcher);
        }

        private void cbFirm_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ComboBox)sender).SelectedValue != null && (((ComboBox)sender).SelectedValue.ToString() != string.Empty))
            {
                ledConnectionOK.Visibility = Visibility.Hidden;
                lblConnectionOK.Visibility = Visibility.Hidden;
                btnNext.Visibility = Visibility.Visible;
            }
            else
            {
                ledConnectionOK.Visibility = Visibility.Visible;
                lblConnectionOK.Visibility = Visibility.Visible;
                btnNext.Visibility = Visibility.Hidden;
            }
        }

        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            UpdateConfigs();

            if (!Util.Sinacor.CheckInstalled())
                CreateRegistry();

            OpenNextStep();
            this.Hide();
        }

        private void cbTNS_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            cbFirm.ItemsSource = null;
            cbFirm.IsEnabled = false;
            ledConnectionOK.Visibility = Visibility.Hidden;
            lblConnectionOK.Visibility = Visibility.Hidden;
            btnNext.Visibility = Visibility.Hidden;
        }

        #endregion        
    }
}
